import React from "react"
import Taro from "@tarojs/taro"
import { Divider } from "@taroify/core"
import GpContainer from "@/components/GpContainer"
import { Text, Navigator, View } from "@tarojs/components"
import GpContactTip from "@/components/GpContactTip"
import GpShareButton from "@/components/GpShareButton"
import GpIcon from "@/components/GpFontIcon"
import GpBlockTitle from "@/components/GpBlockTitle"
import GpInstitutionItemPure from "@/components/GpInstitutionItemPure"
import GpMustReadItem from "@/components/GpMustReadItem"
import GpJumpNavs from "@/components/GpJumpNavs"
import GpCurrentPort from "@/components/GpCurrentPort"
import GpTabbar from "@/components/GpTabbar"
import clsx from "clsx"
import { getNewsDetail, newsLike } from "@/apis/index"
import { pageMapper } from "@/constants/pageMap"
import { makePagePath, commonUrls } from "@/utils/router"
import { cloneDeep, setPageMeta } from "@/utils/common"
import GpHtmlRenderer from "@/components/GpHtmlRenderer"
import styles from "./index.module.scss"
import GpFlowModule from "../../../note/components/GpFlowModule/index"

const ports = [{ text: "资讯详情" }]
type IDetail = {
  id: any
  title: any
  time: any
  topicName: any
  topicId: any
  views: any
  likes: any
  isLike: any
  content: IApiRelative.IGetNewsDetail.IResData["content"]
  /** for page meta, 前80个字 */
  pureContent: string
  /** 培训项目 */
  projects: string[]
  /** 特色标签 */
  tags: string
  /** 引流模块 */
  contentModule: any
}
type IState = {
  detail: IDetail | null
  /**更多资讯 */
  moreNews: any[]
  /**推荐机构 */
  agencys: any[]
}
type IData = {
  pending: boolean
  id: string
}
/** 资讯详情 */
class NewsDetail extends React.Component<unknown, IState> {
  extData: IData
  constructor(props) {
    super(props)
    this.state = {
      detail: null,
      moreNews: [],
      agencys: []
    }
    this.extData = {
      pending: false,
      id: ""
    }
  }
  onShareAppMessage() {}
  /**
   * { id }
   * @param options query data
   */
  onLoad(options: Record<string, any>) {
    this.extData.id = options.id
    this.getDetail()
  }
  componentDidShow() {
    this.setPageInfo(this.state.detail)
  }
  setPageInfo = (detail: INullable<IDetail>) => {
    if (detail) {
      const keywords = [] as string[]
      const _projects = (detail.projects || []).slice(0, 2)
      const tag_1 = detail.tags ? detail.tags[0] : ""
      const tag_2 = detail.tags ? detail.tags[1] || tag_1 : ""
      if (_projects.length >= 2) {
        keywords.push(_projects[0].concat(tag_1))
        keywords.push(_projects[1].concat(tag_2))
      } else {
        keywords.push(_projects[0].concat(tag_1))
      }
      setPageMeta({
        keywords: keywords.join("，"),
        title: `${detail.title}-择艺宝`,
        description: detail.pureContent
      })
    }
  }
  getDetail = () => {
    Taro.showLoading()
    getNewsDetail(this.extData.id)
      .then(res => {
        if (res.data.success) {
          const retData = res.data.data
          const content = retData.content

          const pureContent = retData.summary
          const detail = {
            id: retData.id,
            title: retData.title,
            time: retData.time,
            topicName: retData.topicName,
            topicId: retData.topicId,
            views: retData.views,
            likes: retData.likes,
            isLike: retData.isLike,
            content,
            pureContent,
            projects: retData.projects,
            tags: retData.tags,
            contentModule: retData.contentModule
          } as IDetail
          this.setState({
            detail,
            moreNews: retData.moreNews || [],
            agencys: retData.agencys || []
          })
          this.setPageInfo(detail)
        }
      })
      .finally(() => {
        Taro.hideLoading()
      })
  }
  handleLike = () => {
    if (this.state.detail && this.state.detail.isLike) {
      Taro.showToast({
        title: "你已经点过赞了~",
        icon: "none"
      })
      return
    }
    if (this.extData.pending) return
    this.extData.pending = true
    newsLike(this.extData.id)
      .then(res => {
        if (res.data.success) {
          const _detail = cloneDeep(this.state.detail!)
          _detail.isLike = true
          _detail.likes = _detail.likes + 1
          this.setState({
            detail: _detail
          })
        }
      })
      .finally(() => {
        this.extData.pending = false
      })
  }
  renderContent = () => {
    const { detail } = this.state
    if (!detail) return null
    // 是否有关联模块
    const flowModule = detail.contentModule
    const hasModule = !!flowModule
    const url = makePagePath(pageMapper.columnMain, { id: detail.topicId })
    return (
      <View className="px-30px bg-hex-fff pt-32px">
        <Text className="pt-20px yahei-bold font-bold text-40px leading-64px text-hex-2c2c35">
          {detail.title}
        </Text>
        <View className="mt-32px yahei font-normal text-24px text-left text-hex-b8b8bf">
          <Text>发布时间：{detail.time}</Text>
        </View>
        <Divider className={styles["divider"]} />
        {/* 富文本内容 */}
        {/* className="yahei font-normal text-28px leading-48px text-left text-hex-2c2c35" */}
        {/* <View className="taro_html" dangerouslySetInnerHTML={{ __html: detail.content }}></View> */}
        {detail.content && (
          <View className="taro_html">
            <GpHtmlRenderer htmlBlocks={detail.content.blocks} />
          </View>
        )}
        {/* 引流模块 */}
        {hasModule && (
          <GpFlowModule
            className="my-40px"
            flowModule={{
              remark: flowModule.remark,
              description: flowModule.description,
              displayName: flowModule.displayName,
              id: flowModule.id,
              image: flowModule.cover,
              jumpPageId: flowModule.jumpPageId,
              jumpPageType: flowModule.jumpPageType,
              jumpType: flowModule.jumpType,
              jumpUrl: flowModule.jumpUrl,
              title: flowModule.name,
              isHide: flowModule.isHide
            }}
          />
        )}
        {detail.topicName ? (
          <View className="yahei font-normal text-28px text-hex-B8B8BF mt-24px">
            <Text>*本文收录于专题 </Text>
            <Navigator hoverClass="none" url={url} className="text-hex-1a8cff inline-block">
              <Text>《{detail.topicName}》</Text>
            </Navigator>
          </View>
        ) : null}
        {/* 阅读、转发 */}
        <View className="flex flex-row justify-between items-center mt-25px">
          <View className="yahei font-normal text-26px text-hex-b8b8bf">
            <Text>阅读{detail.views}</Text>
          </View>
          <GpShareButton />
        </View>
        {/* 点赞 */}
        <View className="pt-70px pb-72px flex flex-col justify-center items-center">
          <View className="flex justify-center relative">
            <GpIcon
              icon="icon-youshimianxing"
              size={48}
              color={detail.isLike ? "#1A8CFF" : "#B8B8BF"}
              onClick={this.handleLike}
            />
            {detail.likes ? (
              <Text className={clsx("yahei", styles["good-num"])}>{detail.likes}</Text>
            ) : null}
          </View>
          <View className="yahei font-normal text-36px text-hex-323544 mt-24px">
            <Text>为Ta点赞</Text>
          </View>
        </View>
      </View>
    )
  }
  /** 推荐机构 */
  renderInstitution = () => {
    const { agencys } = this.state
    if (agencys.length <= 0) return null
    return (
      <View className="pt-88px bg-hex-fff">
        <View className="pb-34px px-30px">
          <GpBlockTitle
            title="推荐机构"
            showArrow
            navigatorLink={commonUrls.institution}
            openType="switchTab"
          />
        </View>
        <View className="px-30px pb-31px flex flex-col">
          {agencys.map((l, index) => (
            <GpInstitutionItemPure key={index} institution={l} />
          ))}
        </View>
      </View>
    )
  }
  /** 更多资讯 */
  renderMoreNews = () => {
    const { moreNews } = this.state
    const len = moreNews.length
    if (len <= 0) return null
    return (
      <View className="pt-32px mt-20px bg-hex-fff">
        <View className="pb-34px px-30px">
          <GpBlockTitle title="更多资讯" showArrow navigatorLink={commonUrls.news} />
        </View>
        <View className="px-30px flex flex-col">
          {moreNews.map((l, index) => {
            return (
              <View
                key={index}
                className={clsx({
                  "mb-48px": index !== len - 1
                })}
              >
                <GpMustReadItem mustReadItem={l} />
              </View>
            )
          })}
        </View>
      </View>
    )
  }
  /** 咨询按钮 */
  renderNewsContact = () => {
    return (
      <View className="pt-72px bg-hex-fff">
        <View className="px-30px">
          <GpContactTip showContactBtn={false} />
        </View>
      </View>
    )
  }
  /** 快捷导航 */
  renderJumpNavs = () => {
    return (
      <View className="mt-20px">
        <GpJumpNavs />
      </View>
    )
  }
  render(): React.ReactNode {
    if (!this.state.detail) return null
    return (
      <GpContainer>
        <View>
          {/* 资讯内容 */}
          {this.renderContent()}
          {/* 更多资讯 */}
          {this.renderMoreNews()}
          {/* 资讯按钮 */}
          {this.renderNewsContact()}
          {/* 推荐机构 */}
          {this.renderInstitution()}
          {/* 快捷导航 */}
          {this.renderJumpNavs()}
          {/* 当前位置 */}
          <GpCurrentPort ports={ports} />
        </View>
        {/* 底部导航 */}
        <GpTabbar />
      </GpContainer>
    )
  }
}
export default NewsDetail
